/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.osbosoftware.framework.filtro;


import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.osbosoftware.ejemplo.Usuarios;

/**
 *
 * @author elJefe
 */
public class Filtro implements Filter {

    FilterConfig filterConfig;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest re = (HttpServletRequest) request;
        HttpSession session = re.getSession();
        Usuarios segu = (Usuarios) session.getAttribute("seguridad");
        System.out.println("INTENTO DE ACCESO :" + re.getContextPath());
        System.out.println("direccion :" + re.getLocalAddr());
        System.out.println("url:" + re.getRequestURL());
        if (segu == null) {
            System.out.println("INTENTO DE ACCESO DIRECTO PERMISOS DENEGADOS");
            HttpServletResponse res = (HttpServletResponse) response;
            res.sendRedirect(re.getContextPath() + "/index.jsp");
        } else if (re.getRequestURL().toString().endsWith(".xhtml")) {
            System.out.println("INTENTO DE ACCESO DIRECTO PERMISOS DENEGADOS");
            HttpServletResponse res = (HttpServletResponse) response;
            res.sendRedirect(re.getContextPath() + "/start.jsf");
        } else {
            // verificando permisos
            String rol = segu.getPerfil().toString();
            String pa = re.getContextPath();
            String mo = re.getRequestURI().toString().substring(pa.length(), re.getRequestURI().toString().length());
            PermisosPantalla per = new PermisosPantalla();
            if (per.verPermiso(mo, rol)) {
                chain.doFilter(request, response);
            } else {
                System.out.println("INTENTO DE ACCESO DIRECTO PERMISOS DENEGADOS");
                HttpServletResponse res = (HttpServletResponse) response;
                res.sendRedirect(re.getContextPath() + "/start.jsf");
            }

        }
    }

    public void destroy() {
    }
}
